//
//  TKOAuthViewController.swift
//  TKWBOne
//
//  Created by tiankun on 16/9/2.
//  Copyright © 2016年 1. All rights reserved.
//

import UIKit
import SVProgressHUD

class TKOAuthViewController: UIViewController {

    private lazy var webView = UIWebView()
    override func viewDidLoad() {
        super.viewDidLoad()
        //加载授权页面
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(TKAppKey)&redirect_uri=\(TKRedirectURI)"
        guard let url = URL(string: urlString) else {
            return
        }
        let request = URLRequest(url: url)
        webView.loadRequest(request)
    }
    override func loadView() {
        view = webView
        view.backgroundColor = UIColor.white
        //取消滚动视图
        webView.scrollView.isScrollEnabled = false
        //设置代理
        webView.delegate = self
        title = "登录新浪微博"
        //导航栏按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(back), isBack: true)
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFill))
    }
    @objc private func back() {
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    //自动填充
    @objc private func autoFill() {
        let js = "document.getElementById('userId').value = 'mxtk001@163.com';" + "document.getElementById('passwd').value = 'wbtk921948';"
        webView.stringByEvaluatingJavaScript(from: js)
    }
   

}
//webView代理方法
extension TKOAuthViewController: UIWebViewDelegate {
    /// WebView将要加载请求
    ///
    /// - parameter webView:        webView
    /// - parameter request:        将要加载的请求
    /// - parameter navigationType: 导航类型
    ///
    /// - returns: 是否加载request
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        if request.url?.absoluteString.hasPrefix("\(TKRedirectURI)") == false {
            return true
        }
        if request.url?.query?.hasPrefix("code=") == false {
            print("取消授权")
            back()
            return false
        }
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        print("授权码\(code)")
        TKNetworkManager.shared.loadAccessToken(code: code) { (isSuccess) in
            if !isSuccess {
                SVProgressHUD.showInfo(withStatus: "网络请求失败!")
            } else {
                //发送通知
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: TKUserLoginSuccessedNotification), object: nil)
                //关闭窗口
                self.back()
            }
        }
        return false
    }
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
